<template>
	<view class="content">
		<view class="u-p-t-2">
			<view class="u-bg-white u-radius-8 u-m-20">
				<view class="u-flex u-flex-between  u-border-bottom u-p-t-20 u-p-b-20">
					<text class="u-m-l-20 u-p-b-30 u-p-t-30">头像</text>
					<view class="avatar u-rela u-m-r-20 u-flex u-flex-middle">
						<up-avatar :src="state.avatar" size="40"></up-avatar>
						<button open-type="chooseAvatar" @chooseavatar="onChooseAvatar"
							class="avatar-cover u-flex u-flex-center u-abso">
							<up-icon name="camera" color="#fff" size="22"></up-icon>
						</button>
					</view>
				</view>
				<view class="u-flex u-flex-between u-p-r-20">
					<text class="u-m-l-20 u-p-b-30 u-p-t-30">昵称</text>
					<u-input type="nickname" maxlength="10" v-model="state.name" inputAlign="right" border="none"
						placeholder="请输入您的昵称"></u-input>
				</view>
			</view>
			<view class="u-p-60 u-m-t-80">
				<u-button type="error" shape="circle" :disabled="state.name===''||state.avatar===''" @click="save">保存</u-button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import {
		ref,
		reactive,
		onMounted,
		defineEmits
	} from 'vue'
	import {
		BASE_URL,
		REQUEST_SUCCESS
	} from '/utils/config.js';
	import {
		useAuth
	} from '/composables/useAuth';
	import {
		useCommon
	} from '/composables/useCommon.js';
	import {
		useStore
	} from 'vuex';
	import createApi from '/api/commonAPI.js';
	const commonAPI = createApi(store);
	const store = useStore();
	// 计算属性，用于获取 Vuex 中的状态
	const {
		appid,
		qnUpToken,
		qiniuDomain,
		systemInfo,
		statusHeight,
		navHeight,
		tabbarIndex,
		tabbarShow,
		tabbarHeight,
		bottomSafeHeight,
		isAndroid,
		getQnUpToken,
		reloadAllSystemInfo
	} = useCommon();
	const {
		token,
		user_id,
		userInfo,
		hasAuth,
		session_key,
		SET_TOKEN,
		autoLogin,
		wxLoginByPhone,
		wxGetUserInfo,
		logout,
		refreshAppId,
		SET_USER_INFO,
		SET_AUTH,
	} = useAuth();
	const state = reactive({
		name: '',
		avatar: ''
	})
	//保存nickname
	async function saveName() {
		await commonAPI.setNikeName({
			nick_name: state.name
		}).then(res => {
			if (res.code == REQUEST_SUCCESS) {
				wxGetUserInfo()
			}
		})
	}
	//保存
	async function save() {
		await saveName()
		// 仅在头像有变更时上传
		if (state.newAvatarUrl) {
			await uploadAvatarToServer(state.newAvatarUrl)
		}
		// SET_AUTH(true)
		uni.navigateBack()
	}
	// 监听头像选择事件，并触发上传
	function onChooseAvatar(e) {
		const {
			avatarUrl
		} = e.detail;
		if (!avatarUrl) {
			uni.showToast({
				title: '获取头像失败',
				icon: 'none'
			});
			return;
		}
		// 将选择的头像临时路径保存到 state，用于页面预览
		state.avatar = avatarUrl;
		// 将临时路径保存到新变量，在点击保存时上传
		state.newAvatarUrl = avatarUrl;
	}
	// 统一的上传头像文件方法
	async function uploadAvatarToServer(filePath) {
		uni.uploadFile({
			url: BASE_URL + '/mini/upload_file/',
			filePath: filePath,
			name: 'file', // 对应后端接口的 `file` 字段
			method:'post',
			header: {
				'Content-Type': 'multipart/form-data',
				'token': `${token.value}` // 如果你的上传接口也需要 token
			},
			success: (res) => {
				const data = JSON.parse(res.data);
				if (data.code === REQUEST_SUCCESS) {
					// 上传成功后，更新 userInfo 中的头像链接
					// 注意：这里需要你再调用一个接口来保存新的头像链接
					// 假设接口返回的是一个临时的图片链接，需要再次调用 set_avatar 接口
					commonAPI.setAvatar({
						avatar: data.data // 假设上传接口返回的图片链接在 data.data.url
					}).then(res => {
						if (res.code === REQUEST_SUCCESS) {
							wxGetUserInfo()
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							});
						}
					});
				} else {
					uni.showToast({
						title: data.msg || '头像上传失败',
						icon: 'error'
					});
				}
				state.newAvatarUrl = null; // 清空临时变量
			},
			fail: (err) => {
				console.error('头像上传失败:', err);
				uni.showToast({
					title: '头像上传失败',
					icon: 'error'
				});
				state.newAvatarUrl = null; // 清空临时变量
			}
		});
	}
	onMounted(() => {
		// 页面加载时，使用 Vuex 中的用户信息初始化 state
		state.name = userInfo.value.nick_name || '';
		state.avatar = userInfo.value.avatar || '';
	})
</script>

<style lang="scss" scoped>
	.content {
		height: 100vh;
	}

	.avatar {
		width: 40px;
		height: 40px;
		border-radius: 100%;
		overflow: hidden;
	}

	.avatar-cover {
		background-color: rgba(0, 0, 0, .3);
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		border-radius: 100%;
	}
</style>

<style lang="scss" scoped>
	.content {
		height: 100vh;
	}

	.avatar {
		width: 40px;
		height: 40px;
		border-radius: 100%;
		overflow: hidden;
	}

	.avatar-cover {
		background-color: rgba(0, 0, 0, .3);
		top: 0;
		right: 0;
		left: 0;
		bottom: 0;
		border-radius: 100%;
	}
</style>